var brushImg = new Image();
brushImg.src = 'data:image/png;base64,' + config.brushImg;  
var skin = window.skin ||{};
/**
 * 获取元素对象
 * @param  {string} element 元素id
 * @return {object}         返回元素对象
 */
skin.g = function(element) {
    return document.getElementById(element) || element;
};
/**
 * 转换JSON对象
 * @param  {string} jsonString json字符串
 * @return {object}            json对象
 */
skin.jsonDecode =function(jsonString) {
	return (new Function("return " + jsonString))();
};
/**
 * 显示dom
 * @param  {string} id dom的id
 * @return {void}    无
 */

skin.show = function(id) {
	skin.isShow(id, true);
};
/**
 * 隐藏dom
 * @param  {string} id dom的id
 * @return {void}    无
 */
skin.hide = function(id) {
    skin.isShow(id, false);
};
/**
 * 是否显示
 * @return {Boolean} 返回布尔值
 */
skin.isShow = function(id, flag) {
    skin.g(id).style.display = flag ? 'block' : 'none';
};
/**
 * 添加样式
 * @param {string|object} element   目标元素
 * @param {string} className 样式名称
 */
skin.addClass = function(element, className) { 
	element = skin.g(element)||element;
    var classArray = className.split(/\s+/),
        result = element.className,
        classMatch = " " + result + " ",
        i = 0,
        l = classArray.length;

    for (; i < l; i++) {
         if ( classMatch.indexOf( " " + classArray[i] + " " ) < 0 ) {
             result += (result ? ' ' : '') + classArray[i];
         }
    }

    element.className = result;
};
/**
 * 移除样式
 * @param  {string|object} element   目标元素
 * @param  {string} className 样式名称
 * @return {void}           无
 */
skin.removeClass = function(element, className) { 
	element = skin.g(element)||element; 

    var oldClasses = element.className.split(/\s+/),
        newClasses = className.split(/\s+/),
        lenOld,
        lenDel = newClasses.length,
        j,
        i = 0;  
    for (; i < lenDel; ++i) {
        for(j = 0, lenOld = oldClasses.length; j < lenOld; ++j) {
            if (oldClasses[j] == newClasses[i]) {
            	oldClasses.splice(j, 1);
            	break;
            }
        }
    }
    element.className = oldClasses.join(' ');
};
skin.addEvent = function (obj, type, fn) {
    var isFirefox = typeof document.body.style.MozUserSelect != 'undefined'; 
    if(obj.addEventListener) {
        obj.addEventListener(isFirefox ? 'DOMMouseScroll' : type, fn, false); 
    } else {
        obj.attachEvent('on'+type, fn); 
    }         
    return fn;
};
skin.delEvent = function (obj, type, fn) { 
    var isFirefox = typeof document.body.style.MozUserSelect != 'undefined'; 
    if(obj.removeEventListener) {
        obj.removeEventListener(isFirefox ? 'DOMMouseScroll' : type, fn, false); 
    } else {
        obj.detachEvent('on'+type, fn); 
    }    
};
skin.stopEvent = function (e) {
    e = e||event; 
    if( e.preventDefault )e.preventDefault(); 
    e.returnValue = false;
};
skin.getWheelValue = function (e) { 
    e = e||event; 
    return ( e.wheelDelta ? e.wheelDelta/120 : -( e.detail%3 == 0 ? e.detail/3 : e.detail ) ) ; 
};
/**
 * 把数字转成字符串并加入逗号，如 1,234,567.89
 * @param num
 * @returns {string}
 */
skin.addComma = function (num) {
    var nStr = num + '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
};
/**
 * 执行命令
 * @param {string} order 命令名称
 * @param {string} key 值
 * @return string | void
 */
skin.execOrder = function (order, key) {
    var info = '';
    try { 
        key = (!key ? 'null' : key); 
        info = window.external.SyncRequest(order, key);
    } catch (e) {       
    } 
    return info;
};
/**
 * 最小化当前窗口
 */
skin.minimizeWind = function (id) {
    skin.g(id).onmouseup = function () { 
        skin.addClass(id,"nohover");
        skin.execOrder('minimizeApp');
    };

    skin.g(id).onmouseover = function () {
        skin.removeClass(id,"nohover");
    };
};
/**
 * 关闭当前窗口
 */
skin.closeWind = function (id) {
    skin.g(id).onmouseup = function () {
        skin.execOrder('closeApp');
    }
};
/**
 * 领奖品
 */
skin.getAward = function () {
    var awardParam = {needLogin: false, url: config.getAward};
    skin.execOrder('openUrl', JSON.stringify(awardParam)); 
};
/**
 * 初始化
 */
skin.initIme = function () {

};
/**
 * 在一支笔中打印日志
 * @param {string} str 打印的内容
 */
function Log(str) {   
    try {
        if(window.external.SyncRequest) { 
            window.external.SyncRequest('log', str);
        } else {   //在浏览器控制台中输出        
            console.log(str);
        }
    } catch (e) {}
}
/**
 * 获取点纵坐标
 * @param  {Number} total    当天输入总量
 * @param  {Number} maxTotal 最高输入总量记录
 * @return {Number}          坐标值
 */
function getPointY(total, maxTotal) {
    var max = maxTotal || 1;
    return Math.floor((max - total) / max * (config.table.height - 8)) + 4;
}
/**
 * 获取点横坐标
 * @param  {Number} day    第N天
 * @param  {Number} dayLen 总天数
 * @return {Number}        坐标值
 */
function getPointX(day, dayLen) {
    return Math.floor((6 - day) / 6 * (config.table.width - 8)) + 4;
}
/**
 * 绘制文字输入数量折线图
 * @param  {object} oCanvas   canvas对象
 * @param  {object} inputList 7天文字输入记录
 * @param  {number} maxVal    28天单天输入文字最高纪录
 */
function buildTable (oCanvas, inputList, maxVal) {
    skin.pointList = [];
    oCanvas = oCanvas || skin.g('inputTableCanvas'); 
    var oCtx = oCanvas.getContext("2d");    
    var canvasParent = oCanvas.parentElement;
    oCtx.clearRect(0, 0, oCtx.canvas.width, oCtx.canvas.height);   
    //canvasParent.removeChild(skin.g('bgCanvas'));

    var dLen = inputList.length - 1;
    var oPoint = {
        iX: 0,
        iY: 0
    };

    oCtx.beginPath();
    oCtx.strokeStyle = "#228ee6";
    oCtx.lineWidth = 2;

    oPoint.iX = getPointX(0, dLen);
    oPoint.iY = getPointY(inputList[0].total, maxVal);
    oCtx.moveTo(oPoint.iX, oPoint.iY);
    skin.pointList.push({iX: oPoint.iX, iY: oPoint.iY});
    for (var i = 1, iLen = inputList.length; i < iLen; i++) {
        oPoint.iX = getPointX(i, dLen);
        oPoint.iY = getPointY(inputList[i].total, maxVal);

        oCtx.lineTo(oPoint.iX, oPoint.iY);

        skin.pointList.push({iX: oPoint.iX, iY: oPoint.iY});   
    }
    oCtx.stroke();

    // 绘制圆形的结点
    oCtx.fillStyle = "#ffffff";
    for (i = 0, iLen = inputList.length; i < iLen; i++) {
        oCtx.beginPath();
        oPoint.iX = getPointX(i, dLen);
        oPoint.iY = getPointY(inputList[i].total, maxVal);

        oCtx.arc(oPoint.iX, oPoint.iY, 2, 0, 2*Math.PI);

        oCtx.fill();
        oCtx.stroke();
    }

    //canvasParent.appendChild(createTableBg('bgCanvas'));
    // 初始化趋势图时显示为当天输入详情
    showDataInfo(0, inputList);
    tableInfo(oCanvas, inputList);
    // 初始化标尺
    setGaugeText(inputList);
    // 画趋势图背景
    //drawTableBg();
}
/**
 * 文字输入折线图hover显示
 * @param  {object} oCanvas    canvas对象
 * @param  {object} inputList   7天文字输入记录
 */
function tableInfo (oCanvas, inputList) {
    skin.g("mouseEventMask").onmousemove = function (e) {
        e = window.event ? window.event : e;        
        var mouseX = e.clientX - skin.canvasLeft;
        skin.showInfo = false;
        var dataInfo = skin.g('dataInfo');
        var hrPoint = skin.g('hrPoint');
        var k = -1;
        for (var i = 0, iLen = skin.pointList.length; i < iLen; i++) {
            if (mouseX >= skin.pointList[i].iX - 24 && mouseX <= skin.pointList[i].iX + 24) {
                skin.showInfo = true; 
                k = i;
            } 
        }
        if (skin.showInfo && k > -1) {
            showDataInfo(k, inputList);
            skin.showInfo = false;
        } else {
            skin.showInfo = false; 
        }
        
        skin.hoverInfo = true;
        
    };
    // 鼠标移出趋势图区域，显示当天数据详情
    skin.g("mouseEventMask").onmouseout = function() {
        showDataInfo(0, inputList);
        /*skin.hide('dataInfo');
        skin.hide('hrPoint');*/
    };
}
function showDataInfo (k, inputList) {
    var dataInfo = skin.g('dataInfo');
    var dataInfoText = skin.g('dataInfoText');
    var hrPoint = skin.g('hrPoint');
    var dataInfoPosition = {w: 0, h: 32, paddingLeft: 10};
    dataInfoText.innerHTML = skin.addComma(inputList[k].total);
    dataInfoPosition.w = skin.addComma(inputList[k].total).length * 7 + 21;

    // 在结点上方
    /*skin.removeClass(dataInfo, 'data-info-left');
    skin.removeClass(dataInfo, 'data-info-right');
    skin.addClass(dataInfo, 'data-info-top');
    dataInfo.style.top = (skin.pointList[k].iY + config.table.top - dataInfoPosition.h - 14) + 'px';
    dataInfo.style.left = (skin.pointList[k].iX + config.table.left - (dataInfoPosition.w + dataInfoPosition.paddingLeft * 2) / 2) + 'px';*/

    if (k <= 3) {
        // 在结点左侧
        skin.removeClass(dataInfo, 'data-info-top');
        skin.removeClass(dataInfo, 'data-info-right');
        skin.addClass(dataInfo, 'data-info-left');
        dataInfo.style.top = (skin.pointList[k].iY + config.table.top - dataInfoPosition.h / 2) + 'px';
        dataInfo.style.left = (skin.pointList[k].iX + config.table.left - (dataInfoPosition.w + dataInfoPosition.paddingLeft * 2) - 16) + 'px';
    } else {
        // 在结点右侧
        skin.removeClass(dataInfo, 'data-info-top');
        skin.removeClass(dataInfo, 'data-info-left');
        skin.addClass(dataInfo, 'data-info-right');
        dataInfo.style.top = (skin.pointList[k].iY + config.table.top - dataInfoPosition.h / 2) + 'px';
        dataInfo.style.left = (skin.pointList[k].iX + config.table.left + 16) + 'px';
    }

    dataInfoText.style.width = dataInfoPosition.w + 'px';
    skin.show('dataInfo');

    //var hrPointH = (config.table.height - skin.pointList[k].iY + 7);
    //hrPoint.style.height = (hrPointH < 5 ? 9 : hrPointH) + 'px';
    hrPoint.style.top = (skin.pointList[k].iY + config.table.top - 8) + 'px';
    hrPoint.style.left = (skin.pointList[k].iX + config.table.left - 8) + 'px';
    //hrPoint.getElementsByTagName('p')[1].style.height = (config.table.height - skin.pointList[k].iY - 2) + 'px';
    skin.show('hrPoint');
}

/**
 * 获取canvas在页面的左坐标
 * @param  {object} obj    canvas对象
 */
function getCanvasPositionX (obj) {
    var curLeft = 0;

    if (obj.offsetParent) { 
        while (obj.offsetParent) {
            curLeft += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curLeft += obj.x;
    }
    skin.canvasLeft = curLeft;
}
/**
 * 设置标尺显示
 * @param  {object} inputList   7天文字输入记录
 */
function setGaugeText (inputList) {
    var domList = skin.g("chartGaugeText").getElementsByTagName("p");
    for (var i = 0; i < 7; i ++) {
        if (inputList && inputList[6-i]) {
            domList[i].innerHTML = inputList[6-i].date;
        } else {
            domList[i].innerHTML = "";
        }
    }
}

function setDashboard(speed) {
    var maxSpeed = 960; // 最高速度
    var minDeg = -122; // 0速度的旋转角度
    var maxDeg = 122; // 最高速度的旋转角度
    var speedDive = [0, 10, 60, 200, 500, 960]; // 速度表区间的划分
    var i, len;
    var birdDom = skin.g("maxInputBird");
    var deg = 0, diveDeg;
    if (speed <= 0) {
        deg = minDeg;
    } else if (speed >= maxSpeed) {
        deg = maxDeg;
    } else {
        for (i = 0, len = speedDive.length; i < len; i ++) {
            if (speedDive[i] >= speed) {
                break;
            }
        }
        diveDeg = (maxDeg - minDeg) / (len-1);
        deg = (speed - speedDive[i-1]) / (speedDive[i] - speedDive[i-1]) * diveDeg + minDeg + diveDeg * (i-1);
    }
    birdDom.style.webkitTransform = "rotate(" + deg + "deg)";
}

/**
 * 设置输入总量
 * @param  {number} total  输入总量
 */
function setInputTotal(total) {
    var strTotal = skin.addComma(total);
    /*if (strTotal.length > 8) {
        skin.g('totalInput').style.fontSize = '16px';
    }*/
    skin.g('totalInput').innerHTML = strTotal;
    refreshMedalInfo({key: 'inputTotal', val: total});
}
/**
 * 设置历史最快输入速度
 * @param  {number} record  历史最快输入速度
 */
function setInputRecord(record) {
    skin.g('maxInput').innerHTML = record/* + '<span class="font24">/</span><span class="font18">min</span>'*/;
    setDashboard(record);
}
/**
 * 获取用户级别
 * @param  {number} score 用户积分
 * @return {number}       用户当前级别
 */
function getUserLevel(score) { 
    var k = 0;
    while (score > config.level[k]) { 
        k++;
    }
    return (k > 10) ? 10 : k;
}
/**
 * 设置用户级别
 * @param  {number} score 用户积分
 */
function setUserLevel(score) {
    skin.userLevel = getUserLevel(score); 
    skin.g('levelNum').style.backgroundPosition = -1 * skin.userLevel * config.levelW + 'px ' + config.levelT + 'px';
    skin.g('levelIng').style.width = (score / config.level[skin.userLevel] * config.levelBarW) + 'px';
    skin.g('levelTitle').innerHTML = score + '/' + config.level[skin.userLevel];
}

/**
 * 获取用户输入成就
 * @param {number} inputTotal 用户输入总量
 * @return {object}       用户成就描述
 */
function getInputAchievement (inputTotal) { 
    var k = 0; 
    while (k < writeResult.length && inputTotal > writeResult[k].maxLen) { 
        k++;
    }
    k = (k >= writeResult.length) ? (writeResult.length - 1) : k;
    return writeResult[k];
}
/**
 * 设置用户输入成就
 * @param {number} inputTotal 用户输入总量
 */
function setInputAchievement(inputTotal) {
    var opts = getInputAchievement(inputTotal);  
    var html = '<span>' + opts.description + '</span>';  
    if (opts.keyword) {
        html += '<a href="#" id="openSearch" onmouseup="doSearch(this)" isbook="' + opts.isBook + '" keyword="' + opts.query + '" class="hand">' + opts.keyword + '</a>';
    }
    if (opts.endText) {
        html += opts.endText;
    }
    skin.g('writeResult').innerHTML = html;
}
/**
 * 搜索(成就关键词点击)
 * @param  {string} keyword 搜索关键字
 */
function doSearch (obj) {
    var keyword = obj.getAttribute('keyword');
    if (obj.getAttribute('isbook') == 'true') {
        keyword = '《' + keyword + '》';
    } 
    var openParam =  {
        needLogin: false,
        url: 'http://www.baidu.com/s?wd=' + encodeURIComponent(keyword) + '&tn=SE_baidupinyin'
    };
    skin.execOrder('openUrl', JSON.stringify(openParam));
}
/**
 * 处理勋章点亮数据
 * @param {object} medals 勋章列表
 */
function setMedals (medals) {
    skin.medalsStatu = {}; 
    for (var i = 0, iLen = medals.length; i < iLen; i++) {
        skin.medalsStatu[medals[i]] = 1;
    }
}
/**
 * 刷新勋章列表显示
 */
function buildMedal(li, medalName) {
    var medal = config.medals[medalName];
    li.style.backgroundPosition = (medal.statu ? '0' : config.medalW + 'px') + ' ' + (medal.bgIndex * (-43) + 'px');
    li.setAttribute('medal', medalName);
    li.innerHTML = '<div class="medalmask rel"><p class="abs"></p></div>';
    li.onmouseover = function (e) {
        li.style.backgroundPosition = '0' + ' ' + (medal.bgIndex * (-43) + 'px');
        showMedalInfo(this, 1);
        skin.medalInfo.onmouseover = function () {
            li.style.backgroundPosition = '0' + ' ' + (medal.bgIndex * (-43) + 'px');
            skin.show(skin.medalInfo);
        };
        skin.medalInfo.onmouseout = function () {
            li.style.backgroundPosition = (medal.statu ? '0' : config.medalW + 'px') + ' ' + (medal.bgIndex * (-43) + 'px');
            if (!skin.isHoverMedal) {
                skin.hide(skin.medalInfo);
            }
        };
    };
    li.onmouseout = function (e) {
        li.style.backgroundPosition = (medal.statu ? '0' : config.medalW + 'px') + ' ' + (medal.bgIndex * (-43) + 'px');
        showMedalInfo(this, 0);
    };
    return li;
}
/**
 * 显示|隐藏勋章详情浮窗
 * @param  {object}  obj     li元素
 * @param  {number} isHover 是（1）否（0）点亮
 */
function showMedalInfo(obj, isHover) {
    skin.isHoverMedal = isHover;
    if (isHover) { 
        var num = parseInt(obj.getAttribute('num'));
        num = (num > skin.medalLineCount - 1) ? (num - skin.medalLineCount) : num;
        var left = obj.offsetLeft + config.medalInfoOf.left + (parseInt(obj.parentNode.style.left) || 0);
        if (num % 10  < 7) {
            skin.medalInfo.style.left = left + 'px';
            skin.removeClass(skin.medalInfo, 'left');
        } else {
            skin.medalInfo.style.left = left + 'px';
            skin.addClass(skin.medalInfo, 'left');
        }        
        skin.medalInfo.style.top = (obj.offsetTop + config.medalInfoOf.top) + 'px';
        // 设置勋章详情浮窗
        setMedalInfo(obj.getAttribute('medal'));
        skin.show(skin.medalInfo);
    } else {
        skin.hide(skin.medalInfo);
    }
}
/**
 * 设置勋章详情
 */
function setMedalInfo (medalName) {
    var medal = config.medals[medalName]; 
    var html = '';
    skin.g('medalTitle').innerHTML = medal.title;
    
    html += '<p>' + medal.desc + '</p>';
    if (typeof medal['plan'] != 'undefined' && medal.plan.total < medal.plan.minVal && medal.statu == 0) {
        html += '<p>进度:<span class="plan">' + medal.plan.total + '/' + medal.plan.minVal + '</span>' + medal.plan.unit + '</p>';
    }
    if (typeof medal['fireOrder'] != 'undefined') {
        html = html.replace('<a>', '<a href="#" onclick="openPlugin(\'' + medal['fireOrder'] + '\')">');
        //html[html.length] = '<p class="go-finish"><span onclick="openPlugin(\'' + medal['fireOrder'] + '\')">去做任务</span></p>';
    }
    skin.g('medalText').innerHTML = html;
}
function openPlugin(openType) {    
    if (openType == 'setDefault') {
        skin.execOrder('setDefault');
    } else {
        skin.execOrder('openPlugin', openType);
    }
}
/**
 * 处理勋章显示
 * @param {object} medals 勋章列表
 */
function proccessMedals(medals) { 
    setMedals(medals);
    var k = 0;
    var li;
    skin.medalList.innerHTML = '';
    // 重新获取勋章列表的状态
    for (var m in config.medals) {
        // 创建顺序索引值
        config.medals[m]['mIndex'] = k;
        config.medals[m].statu = skin.medalsStatu[m] ? 1 : 0; 
        li = document.createElement('li');
        li.setAttribute('num', k+'');
        skin.medalList.appendChild(buildMedal(li, m));
        k++;
    }
    skin.medalList.style.width = (Math.ceil(k) * (config.medalW +  config.medalL)) + 'px';
    skin.medalLineCount = Math.ceil(k);
}

/**
 * 勋章列表滚动显示
 * @param  {number} direction 方向(1/-1)
 */
function scrollMedalsBox (direction) {
    skin.hide(skin.medalInfo);
    var w = config.medalScrollW;
    var items = skin.g('medalNav').getElementsByTagName('span');
    if (direction > 0) {
        //skin.medalList.className = 'prevPage_1';
        skin.medalList.style.left = '0';
        skin.removeClass(items[1], 'cur');
        skin.addClass(items[0], 'cur');
        skin.removeClass('medalNext', 'right-arrow-disabled');
        skin.addClass('medalPrev', 'left-arrow-disabled');
    } else {
        //skin.medalList.className = 'nextPage_1';
        skin.medalList.style.left = -w + 'px';
        skin.removeClass(items[0], 'cur');
        skin.addClass(items[1], 'cur');
        skin.removeClass('medalPrev', 'left-arrow-disabled');
        skin.addClass('medalNext', 'right-arrow-disabled');
    }
}
/**
 * 绑定滚轮事件
 * @param  {object} element    鼠标触发对象
 * @param  {function} scrollFunc 处理函数
 */
function proccessScrollEvent(element, scrollFunc) {
    skin.addEvent(element, 'mousewheel', function (e) {
        skin.stopEvent(e);
        var wheelDelta = skin.getWheelValue(e);
        scrollFunc(wheelDelta);
    });
}
/**
 * 已登录用户--账号设置
 */
function proccessUserSetting() {
    skin.hide('userItems');
    skin.userItemBox = false;
    var userParam = {needLogin: false, url: config.userSettingUrl};
    skin.execOrder('openUrl', JSON.stringify(userParam)); 
}
/**
 * 已登录用户--退出
 */
function proccessLoginOut(){
    skin.hide('userItems');
    proccessLoginIme(false);
    skin.userItemBox = false;
}
/**
 * 已登录用户--显示用户设置
 */
function proccessUserItems() {
    if (skin.userItemBox) {
        skin.userItemBox = false;
        skin.hide('userItems');
    } else {   
        skin.userItemBox = true;     
        skin.show('userItems');
    }
}
/**
 * 处理未登录情况下提示相关事件
 */
function proccessUnloginMedal() {
    if (!skin.bindUnloginMedal) {
        skin.bindUnloginMedal = true;
        // 未登录
        // 这中间的代码已被删除了 by liangweibin
    }    
}
/**
 * 刷新-设置经验和金币（供客户端调用）
 * @param {object} data 对应信息
 */
function setExpCoin (data) {
    // 设置等级
    setUserLevel(data.exp);
    // 设置金币
    skin.g('coin').innerHTML = data.coin;
}
/**
 * 刷新--点亮某个勋章（供客户端调用）
 * @param {object} data 勋章信息
 */
function fireMedal (data) {
    config.medals[data.medal].statu = 1;
    var medal = config.medals[data.medal];
    var li = skin.medalList.getElementsByTagName('li')[medal.mIndex];
    buildMedal(li, data.medal);    
}
/**
 * 设置用户信息（供客户端调用）
 * @param {object} data 用户信息列表
 */
function setUserInfo (data) {
    processHeadMask(data.passport.login);
    if (data.passport.login) {
        skin.g('uName').innerHTML = data.passport.uname + '<div id="userBox" onclick="proccessUserItems()" class="userbox abs"><div id="userItems" class="user-items abs"><p onclick="proccessUserSetting()" id="userSetting">账号设置</p><p onclick="proccessLoginOut()" id="logout">退出</p></div></div>';
        // 设置头像
        setUserHead(data.passport.uid, data.passport.uname);   
        skin.removeClass('isLogined', 'unlogin');
        skin.hide('unloginMsg');
        skin.show('loginMsg');
        skin.isLogin = true;
        // 首次登录，弹一个tips
        showFullExchangeTip();
        skin.hide('full_tip_login');
    } else {
        skin.g('uName').innerHTML = '<a class="loginbtn button" onclick="proccessLoginIme(true) ">登录</a>';
        // 设置未登录头像
        skin.g("uHead").src = config.unloginHead;
        skin.addClass('isLogined', 'unlogin');
        skin.hide('loginMsg');
        skin.show('unloginMsg');
        skin.isLogin = false;
        showFullLoginTip();
        skin.hide('full_tip_exchange');
    }
    // 设置等级
    setUserLevel(data.exp);
    // 设置金币
    skin.g('coin').innerHTML = data.coin;
    // 设置勋章
    proccessMedals(data.medals);
}
/**
 * 显示未登录medal遮罩图层（供客户端调用）
 */
function showTips() {
    // 绑定事件
    proccessUnloginMedal();
}
/**
 * 是否显示未登录medal遮罩图层（供客户端调用）
 */
function isNoTipsEcho(val) {
    if (!val){
        // 绑定事件
        proccessUnloginMedal();
    }
}
/**
 * 设置输入信息（供客户端调用）
 * @param  {object} data 用户近期输入信息数据
 */
function setInputData (data) {
    var drawData;
    skin.inputData = data;
    skin.inputData.dailyRecords = proccessInputData(data.dailyRecords);
    skin.recordsLen = skin.inputData.dailyRecords.length;
    // 天数处理成7的倍数
    if (skin.recordsLen >= 7 && skin.recordsLen % 7 > 0) {
        skin.recordsLen -= skin.recordsLen % 7;
        skin.inputData.dailyRecords = skin.inputData.dailyRecords.slice(0, skin.recordsLen);
    }
    if (skin.recordsLen <= 7) {
        drawData = skin.inputData.dailyRecords;
        skin.tablePageTotal = 1;
        skin.tablePageNum = 1;
        skin.addClass('prevDays', 'left-arrow-disabled');
        skin.addClass('nextDays', 'right-arrow-disabled');
    } else {
        skin.tableDays = skin.inputData.dailyRecords.length;
        skin.tablePageTotal = Math.ceil(skin.tableDays / 7);
        skin.tablePageNum = skin.tablePageTotal;
        drawData = skin.inputData.dailyRecords.slice(0, 7);
        skin.removeClass('prevDays', 'left-arrow-disabled');
    }
    // 绘制近期输入趋势图
    buildTable(skin.g('inputTableCanvas'), drawData, skin.inputData.maxDailySum);
    // 设置查看输入趋势图
    proccessChangeTable();
    // 输入总量
    setInputTotal(skin.inputData.inputTotal);
    // 历史输入最快速度
    setInputRecord(skin.inputData.maxSpeed);
    // 设置用户输入成就
    setInputAchievement(skin.inputData.inputTotal);
    // 若输入总量、历史速度皆为0，则显示一个tips
    if (!skin.inputData.inputTotal && !skin.inputData.maxSpeed) {
        setTimeout(function(){
            skin.show('tips00');
        }, 500);
    } else {
        skin.hide('tips00');
        setTimeout(function(){
            skin.hide('tips00');
        }, 501);
    }
}
/**
 * 刷新当日输入信息（供客户端调用）
 * @param  {object} data 最新的输入信息数据
 */
function refreshTodayInput(data) {
    // 更新用户输入数据--今天输入量|输入总量|历史输入最快速度
    skin.inputData.dailyRecords[0].total = data.inputToday;
    skin.inputData.inputTotal = data.inputTotal;
    skin.inputData.maxSpeed = data.maxSpeed;
    skin.inputData.maxDailySum = (skin.inputData.maxDailySum > data.inputToday) ? skin.inputData.maxDailySum : data.inputToday;

    if (skin.tablePageNum == 1) {
        // 重绘近期输入趋势图
        buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(0, 7), skin.inputData.maxDailySum);
    }    
    // 输入总量
    setInputTotal(skin.inputData.inputTotal);
    // 历史输入最快速度
    setInputRecord(skin.inputData.maxSpeed);
    // 设置用户输入成就
    setInputAchievement(skin.inputData.inputTotal);
    // 若输入总量、历史速度皆为0，则显示一个tips
    if (!skin.inputData.inputTotal && !skin.inputData.maxSpeed) {
        setTimeout(function(){
            skin.show('tips00');
        }, 500);
    } else {
        skin.hide('tips00');
        setTimeout(function(){
            skin.hide('tips00');
        }, 501);
    }
}
/**
 * 刷新表情进度信息（供客户端调用）
 * @param  {object} opts 刷新参数
 */
function refreshMedalInfo(opts) {
    var order = config.orderMap[opts.key];
    for (var i = 0, iLen = order.length; i < iLen; i++) {
        config.medals[order[i]].plan.total = opts.val;
    }
}
/**
 * 返回有效数据列表
 * @param  {object} list 28天输入数据列表
 * @return {object}      计算后的数据列表
 */
function proccessInputData(list) {
    var len = list.length;
    var count = Math.ceil(list.length / 7);
    var num = len % 7;
    var c = 0;
    var k = 0;
    for (var iLen = list.length - 1, i = iLen; i >= 0; i--) {        
        if (list[i].total > 0) {
            break;
        }
        k++;
    }
    if (k >= num) {
        c = num;
        c = c +  Math.floor((k - num) / 7) * 7;
        // 至少保留一个趋势图
        c = (c == len) ? len - 7 : c;
    }

    return  (c== 0) ? list : list.slice(0, len - c); 
}
/**
 * 设置查看近期输入趋势图
 */
function proccessChangeTable() {
    skin.g('prevDays').onclick = function () {
        if (skin.tablePageNum > 1) {
            skin.tablePageNum--;  
            var startIndex = (skin.tablePageTotal - skin.tablePageNum) * 7;             
            if (skin.tablePageNum == 1) {
                buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(startIndex), skin.inputData.maxDailySum);
            }  else {
                buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(startIndex, startIndex + 7), skin.inputData.maxDailySum);
            }   
        }  
        if (skin.tablePageNum == 1 || skin.tablePageTotal == 1) {
            skin.addClass(this, 'left-arrow-disabled');
        } else {
            skin.removeClass(this, 'left-arrow-disabled');
        }
        if (skin.tablePageTotal > 1) {
            skin.removeClass('nextDays', 'right-arrow-disabled');
        }
    };
    skin.g('nextDays').onclick = function () {  
        if (skin.tablePageNum < skin.tablePageTotal) {
            skin.removeClass(this, 'right-arrow-disabled');
            skin.tablePageNum++;
            var startIndex = (skin.tablePageTotal - skin.tablePageNum) * 7; 
            buildTable(skin.g('inputTableCanvas'), skin.inputData.dailyRecords.slice(startIndex, startIndex + 7), skin.inputData.maxDailySum);   
        }  
        if (skin.tablePageNum == skin.tablePageTotal) {
            skin.addClass(this, 'right-arrow-disabled');
        } else {
            skin.removeClass(this, 'right-arrow-disabled');
        }
        if (skin.tablePageTotal > 1) {
            skin.removeClass('prevDays', 'left-arrow-disabled');
        }
    }
}
/**
 * 设置用户头像
 * @param {string} uid 用户id
 * @param {string} uname 用户名称
 */
function setUserHead (uid, uname) {
    var url = 'http://ime.baidu.com/?act=lottery&k=getimg&t=geturl&uid=' + uid + '&uname=' + encodeURIComponent(uname);
    try {
        baidu.ajax.request(url + '&rnd=' + (+new Date()),{ 
            method: 'GET',
            data: '',       
            timeout: 3000,
            onsuccess:function (xhr, result) {
                skin.g("uHead").src = result;
            },
            onfailure: function () {
            },
            ontimeout: function (xhr) {
            }
        });
    } catch (e) {}
}
/**
 * 设置头像可点击登录
 * @param {Boolean} isLogin [description]
 */
function processHeadMask(isLogin) {
    var logined = isLogin ? '1' : '0';
    skin.g('headMask').setAttribute('logined', isLogin);
    if (logined == '0') {
        skin.g('headMask').onclick = function () {
            skin.execOrder('openLoginWnd1');
        }        
    } else {
        skin.g('headMask').onclick = function () {
            var userParam = {needLogin: false, url: config.userSettingUrl};
            skin.execOrder('openUrl', JSON.stringify(userParam)); 
        }
    }
}
/**
 * 登录|退出
 * @param  {Boolean} val 是否为登录操作
 */
function proccessLoginIme(val) {
    if (val) {
        skin.execOrder('openLoginWnd'); 
    } else {
        skin.execOrder('logout');
    }    
}
/**
 * 上传本地图片
 * @param  {object} opts 上传所需参数
 */
function uploadLocalImage (opts) {
    if (typeof opts == 'string') {
        opts = JSON.parse(opts);
    }
    var _type = replaceReg(opts.type);
    if (typeof window['proccessUpload' +_type] == 'function') {
        window['proccessUpload' + _type](opts);
    }
}
/**
 * 获取分享地址
 * @return {string} 分享地址
 */
function getShareURL() {
    var url = config.share.url;
    var items = config.share.opts;
    var k = 1;
    for (var c in items) {
        if (k == 1) {
            k = '?';
        } else {
            k = '&';
        }
        url = url + k + c + '=' + items[c];
    }
    return url;
}
/**
 * 设置分享地址
 * @param {string} key   参数名称
 * @param {string|number|bool} value 参数值
 */
function  setShareURL(key, value) {
    config.share.opts[key] = value;
}
/**
 * 绑定分享事件
 */
function initShareButton() {
    var items = config.share.items;
    var opts;
    for (var s in items) {        
        skin.g(items[s]).onclick = function () { 
            skin.hide('shareBox');   
            if ('weixin' == this.id) {
                opts = {type: this.id, url: config.share.weixinSign};
            } else {
                opts = {type: this.id};
            }      
            window.setTimeout(function (){
				skin.execOrder('share', JSON.stringify(opts)); 
			}, 30);           
        }
    }
}
/**
 * 处理上传提示(供客户端调用)
 * @param  {bool} result 上传结果
 */
function didShare(result) {
    if (result == "true") {
        showUpload(false);
    } else {
        showUpload(false);
        skin.show("errUpload");
    }
}
function showUpload(show) {
    if (show) {
        skin.show("doUpload");  
        load.loading();
    } else {
        skin.hide("doUpload");
        load.clearTimer();
    }
}
/**
 * 关闭上传错误提示弹窗
 */
function closeErrDialog() {
    skin.hide("errUpload");
}
/**
 * 执行分享(供客户端调用)
 * @param  {object} opts 分享内容(图片地址,分享类型)
 */
function doShare(opts) {    
    setShareURL('pic', opts.imgSrc);
    setShareURL('to', opts.shareType);
    var shareOpts = {needLogin: false, url: getShareURL()};
    skin.execOrder('openUrl', JSON.stringify(shareOpts)); 
}
/**
 * 把字符串转换为首字母大写形式
 * @param  {string} keyword 是字符串
 * @return {string}         新字符串
 */
function replaceReg(keyword) {
    var reg = /\b(\w)|\s(\w)/g;
    return keyword.replace(reg, function (m) { return m.toUpperCase(); });
}

function showFullLoginTip () {
    // todo: 读取标记判断是否曾经弹过
    if (skin.execOrder('isNoLoginTips') * 1) return;
    skin.show('full_tip_login');
    skin.g('full_tip_login_close_1').onclick = skin.g('full_tip_login_close_2').onclick = function () {
        hideFullLoginTip();
    };
    skin.g('full_tip_login_login').onclick = function () {
        skin.execOrder('openLoginWnd1');
        hideFullLoginTip();
    };
}
function hideFullLoginTip () {
    skin.execOrder('setNoLoginTips');
    skin.hide('full_tip_login');
}

function showFullExchangeTip () {
    if (skin.execOrder('isNoTips') * 1) return;
    skin.show('full_tip_exchange');
    skin.g('full_tip_exchange_close').onclick = function () {
        hideFullExchangeTip();
    };
    skin.g('full_tip_exchange_exchange1').onclick = skin.g('full_tip_exchange_exchange2').onclick = function () {
        skin.getAward();
        hideFullExchangeTip();
    };
}

function hideFullExchangeTip () {
    skin.execOrder('setNoTips');
    skin.execOrder('setNoLoginTips');
    skin.hide('full_tip_exchange');
}


var load = {
    totle: 12,
    width: 32,
    count: 0,
    loadTimer: null,
    obj: skin.g("load"),
    clearTimer: function () {
        if (this.loadTimer) {
            window.clearTimeout(this.loadTimer);
            this.loadTimer = null;
        }
    },
    loading: function () {
        ++ this.count;
        if (this.count == this.totle) {
            this.count = 0;
        }
        this.obj.style.backgroundPosition = (-1 * this.count * 32) + "px 0";               
        window.setTimeout(function () {
            load.loading();
        }, 80);
    }
};

/*测试数据*/
function testData(str) {
    skin.g('test_data').innerHTML += '<br />' + str;
}
